const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'


router.post('/getUser', async (req, res) => {
    //token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select departmentId from user_role where username = ?'
    db.base(sql, result.username, response_temp => {
        console.log(response_temp)
        if (response_temp != null && response_temp[0].departmentId == 999) {
            sql = 'SELECT * from user'
            db.base(sql, null, response_user => {
                console.log(response_user)
                sql = 'SELECT * from role'
                db.base(sql, null, response_role => {
                    console.log(response_user)
                    console.log(response_role)
                    for (i = 0; i < response_user.length; i++) {
                        for (j = 0; j < response_role.length; j++) {
                            if (response_role[j].role_id == response_user[i].role_id) {
                                response_user[i].roleName = response_role[j].role_name
                            }
                        }
                    }
                    res.json(response_user)
                })
            })
        }


    })
})

router.post('/getRole', async (req, res) => {
    //token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select departmentId from user_role where username = ?'
    db.base(sql, result.username, response_temp => {
        console.log(response_temp)
        if (response_temp != null && response_temp[0].departmentId == 999) {
            sql = 'SELECT role_id,role_name from role'
            db.base(sql, null, response_role => {
                res.json(response_role)
            })
        }


    })
})

module.exports = router
